package eu.gegenleitner.esspacc.xmlSignature;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class XMLSignatureRequester {
	public final static String createXMLSignatureRequestPartOne = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
			+ "<sl:CreateXMLSignatureRequest xmlns:sl=\"http://www.buergerkarte.at/namespaces/securitylayer/1.2#\">"
			+ "<sl:KeyboxIdentifier>SecureSignatureKeypair</sl:KeyboxIdentifier>"
			+ "<sl:DataObjectInfo Structure=\"enveloping\">"
			+ "<sl:DataObject>"
			+ "<sl:XMLContent>";
	public final static String createXMLSignatureRequestPartTwo = "</sl:XMLContent>"
			+ "</sl:DataObject>"
			+ "<sl:TransformsInfo>"
			+ "<sl:FinalDataMetaInfo>"
			+ "<sl:MimeType>text/plain</sl:MimeType>"
			+ "</sl:FinalDataMetaInfo>"
			+ "</sl:TransformsInfo>"
			+ "</sl:DataObjectInfo>"
			+ "</sl:CreateXMLSignatureRequest>";
	
	/**
	 * TODO: SSLSocket-Connection
	 * TODO: no Hardcoded Connectionparameters
	 * @param toSign
	 * @return
	 */
	public String getXMLSignature(String toSign) {
		String xmlSignature = "";
		try {
			Socket socket = new Socket("127.0.0.1", 3495);
			OutputStream out = socket.getOutputStream();
			InputStream in = socket.getInputStream();
			
			String request = createXMLSignatureRequestPartOne + toSign + createXMLSignatureRequestPartTwo;
			
			out.write(request.getBytes());
			@SuppressWarnings("resource")
			Scanner s = new Scanner(in).useDelimiter("\\A");
			String response = s.hasNext() ? s.next() : "";
			
			s.close();
			out.close();
			in.close();
			socket.close();
			
			xmlSignature = response;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return xmlSignature;
	}
	
	/**
	 * ONLY FOR TESTING
	 * TODO: Delete this TESTMETHOD
	 * @return
	 */
	public String getXMLSignature() {
		String xmlSignature = "";
		try {
			File file = new File("Signed.xml");
			BufferedReader br = new BufferedReader(new FileReader(file));
			while(br.ready()) {
				xmlSignature += br.readLine();
			}
			br.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
		return xmlSignature;
	}
}
